package com.sto.stoapp.upload;

import java.util.List;

import android.content.Context;
import android.os.Handler;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.sto.stoapp.db.StoFilePreference;
import com.sto.stoapp.db.manager.ErrorRecordManager;
import com.sto.stoapp.db.manager.UploadDataManager;
import com.sto.stoapp.http.HttpManager;
import com.sto.stoapp.http.URLActions;
import com.sto.stoapp.http.request.upload.BusinessBaseInfo;
import com.sto.stoapp.http.request.upload.ScanDataRequest;
import com.sto.stoapp.http.response.upload.ErrorRecordInfo;
import com.sto.stoapp.http.response.upload.UploadResponse;
import com.sto.stoapp.log.ExceptionLog;
import com.sto.stoapp.status.EnumTableNames;
import com.sto.stoapp.thread.BaseThread;
import com.sto.stoapp.util.Helper;
import com.sto.stoapp.util.TraceUtil;

/**
 * 上传数据线程
 * 
 * @author
 * 
 */
public class UploadDataThread extends BaseThread {

	private Context context;
	private Handler handler;
	private EnumTableNames status;

	public UploadDataThread(Context context, EnumTableNames status,
			Handler handler) {
		super(context);
		this.context = context;
		this.status = status;
		this.handler = handler;
	}

	@Override
	public void run() {
		super.run();
		List<Object> infos = UploadDataManager.getInstance(context)
				.queryUploadData(status);
		if (infos == null || infos.size() == 0) {
			handler.obtainMessage(status.ordinal(), UploadDataService.NO_DATAS)
					.sendToTarget();
			return;
		}
		ScanDataRequest request = new ScanDataRequest();
		request.cnt = infos.size() + "";

		BusinessBaseInfo bizInfo = (BusinessBaseInfo) infos.get(0);
		request.mty = "0" + bizInfo.opCode;
		request.opRecord = infos;
		request.org = StoFilePreference.getInstance(context).getSiteCode();
		request.sessionId = StoFilePreference.getInstance(context)
				.getSessionId();
		request.tid = StoFilePreference.getInstance(context).getMachineCode();
		request.trace = TraceUtil.getTraceTimes();
		String str = request.buildToRequestString();
		HttpManager mgr = new HttpManager();
	//	ExceptionLog.writeLog("发送:", str);
		final String response = mgr.doPostClient(str, StoFilePreference
				.getInstance(context).getServerIp()
				+ URLActions.UPLOAD_MESSAGE_ACTION);
	//	ExceptionLog.writeLog("收到:", response);
		Gson gson = new Gson();
		UploadResponse uploadResponse = null;
		try {
			uploadResponse = gson.fromJson(response,
					new TypeToken<UploadResponse>() {
					}.getType());
		} catch (JsonSyntaxException e1) {
			e1.printStackTrace();
			ExceptionLog.writeLog("UploadDataService ", "UploadResponse 解析出错："
					+ response + " \n Exception:" + e1.toString());
			showMsg("上传数据服务器返回数据解析出错");
			handler.obtainMessage(status.ordinal(), UploadDataService.ERROR)
					.sendToTarget();
			return;
		}

		if (uploadResponse == null) {
			showMsg("上传数据服务器未返回数据");
			ExceptionLog.writeLog("UploadDataService", "上传数据服务器未返回数据 response:"
					+ response);
			handler.obtainMessage(status.ordinal(), UploadDataService.ERROR)
					.sendToTarget();
			return;
		}

		if (UploadDataService.SUCCESS.equals(uploadResponse.respCode)) {
			for (ErrorRecordInfo error : uploadResponse.errorRecord) {
				if (ErrorRecordManager.getInstance(context).querySizeByUuid(
						error.respPdaUuid) == 0) {
					StringBuffer buffer = new StringBuffer();
					buffer.append("单号：");
					buffer.append(error.respWaybillNo);
					buffer.append(error.respErrorDescription);
					showMsg(buffer.toString());
				}

			}

			ErrorRecordManager.getInstance(context).insertOrReplace(
					uploadResponse.errorRecord, uploadResponse.org);

			handler.obtainMessage(status.ordinal(), UploadDataService.SUCCESS)
					.sendToTarget();
		} else {
			handler.obtainMessage(status.ordinal(), UploadDataService.ERROR)
					.sendToTarget();
		}

	}

	private void showMsg(final String text) {
		handler.post(new Runnable() {

			@Override
			public void run() {
				Helper.showToast(context, text);
			}
		});
	}
}
